package com.zlt.appparking.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.zlt.appparking.config.AlipayConfig;
import com.zlt.appparking.dto.AppointmentDTO;
import com.zlt.appparking.entity.*;
import com.zlt.appparking.mapper.AppointmentMapper;
import com.zlt.appparking.mapper.CarAddressMapper;
import com.zlt.appparking.mapper.ParkingLotMapper;
import com.zlt.appparking.mapper.UserCreditMapper;
import com.zlt.appparking.service.AppointmentService;
import com.zlt.appparking.utils.StringUtil;
import com.zlt.appparking.vo.ActiveUser;
import com.zlt.appparking.vo.AppointmentVO;
import com.zlt.appparking.vo.ParkingLotVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AppointmentServiceImpl implements AppointmentService {


    @Autowired
    private UserCreditMapper userCreditMapper;

    @Autowired
    private CarAddressMapper carAddressMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;

    @Autowired
    private ParkingLotMapper parkingLotMapper;


    @Override
    @Transactional
    public boolean insertAppointment(AppointmentDTO appointmentDTO) throws ParseException {

        // 判断是否登录
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        if (activeUser == null) {
            throw new RuntimeException("预约失败,用户未登录");
        }


        Appointment appointment = new Appointment();
        BeanUtils.copyProperties(appointmentDTO, appointment);
        //设置一个uuid  作为订单编号


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String t = StringUtil.getCurrentTime();
        Date date = simpleDateFormat.parse(t);

        appointment.setApOrderTime(date);
        appointment.setApNo(StringUtil.uuid());
        appointment.setApNoState((byte) 1);
        appointment.setApDeposit(new BigDecimal(5));

        //查询信誉分
        // 查询用户的信誉分
        UserCreditExample userCreditExample = new UserCreditExample();
        userCreditExample.createCriteria().andAuIdEqualTo(activeUser.getAuId());
        UserCredit userCredit = userCreditMapper.selectByExample(userCreditExample).get(0);

        if (userCredit.getUcScore().compareTo(new BigDecimal(60)) < 0) {

            // 查询停车场是否还有剩余车位
            CarAddressExample carAddressExample = new CarAddressExample();
            carAddressExample.createCriteria().andPlIdEqualTo(appointmentDTO.getPlId());

            CarAddress carAddress = carAddressMapper.selectByExample(carAddressExample).get(0);
            if (carAddress.getCaSurplus() == 0) {
                throw new RuntimeException("预约失败，暂无剩余车位");
            }

            // 锁定车位，车位数量-1
            carAddress.setCaSurplus(carAddress.getCaSurplus() - 1);
            carAddressMapper.updateByPrimaryKeySelective(carAddress);
            int i = appointmentMapper.insertSelective(appointment);

            //调用支付接口  返回值 是response   response.issuccess();
            String s = "预定单支付";
            AlipayConfig alipayConfig = new AlipayConfig();


            try {

                AlipayTradeAppPayResponse alipayTradeAppPayResponse = alipayConfig.sendRequestToAlipay(appointment.getApNo(), appointment.getApDeposit().floatValue(), s);
                boolean success = alipayTradeAppPayResponse.isSuccess();
                System.out.println("success : "+success);
                return success;
            } catch (AlipayApiException e) {
                e.printStackTrace();
                return false;
            }

        } else {
            appointment.setApNoState((byte) 0);

            // 查询停车场是否还有剩余车位
            CarAddressExample carAddressExample = new CarAddressExample();
            carAddressExample.createCriteria().andPlIdEqualTo(appointmentDTO.getPlId());

            CarAddress carAddress = carAddressMapper.selectByExample(carAddressExample).get(0);
            if (carAddress.getCaSurplus() == 0) {
                throw new RuntimeException("预约失败，暂无剩余车位");
            }

            // 锁定车位，车位数量-1
            carAddress.setCaSurplus(carAddress.getCaSurplus() - 1);
            carAddressMapper.updateByPrimaryKeySelective(carAddress);

            int i = appointmentMapper.insertSelective(appointment);
            return i > 0;
        }

    }

    @Override
    public boolean cancelReserve(Integer apId) {
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        if (activeUser == null) {
            throw new RuntimeException("取消失败,用户未登录");
        }

        Appointment appointment = appointmentMapper.selectByPrimaryKey((long) apId);

        appointment.setApState((byte) 1);
        int i = appointmentMapper.updateByPrimaryKeySelective(appointment);

        return i > 0;
    }

    @Override
    public List<AppointmentVO> queryList() {
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        if (activeUser == null) {
            throw new RuntimeException("查找失败,用户未登录");
        }

        // 查询当前 登录人的订单信息
        AppointmentExample appointmentExample = new AppointmentExample();
        appointmentExample.createCriteria().andAuIdEqualTo(activeUser.getAuId());
        List<Appointment> appointmentList = appointmentMapper.selectByExample(appointmentExample);

        ParkingLotVO parkingLotVO = new ParkingLotVO();
        for (Appointment appointment : appointmentList) {
            if (appointment.getPlId() != null) {
                ParkingLot parkingLot = parkingLotMapper.selectByPrimaryKey(appointment.getPlId());
                BeanUtils.copyProperties(parkingLot, parkingLotVO);
            }
        }

        return appointmentList.stream()
                .map(appointment -> {
                    AppointmentVO appointmentVO = new AppointmentVO();
                    BeanUtils.copyProperties(appointment, appointmentVO);
                    appointmentVO.setParkingLotVO(parkingLotVO);
                    return appointmentVO;
                })
                .collect(Collectors.toList());

    }
}
